#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <numeric>
using namespace std;

int find(vector<int> &pa, int x)
{
        return pa[x] == x ? x : pa[x] = find(pa, pa[x]);
}

int merge(vector<int> &pa, int x, int y)
{
        int fx = find(pa, x);
        int fy = find(pa, y);
        if(fy != fx){
                pa[fx] = fy;
                return 1;
        }else{
                return 0;
        }
}

int main()
{
        int n, m;
        cin >> n >> m;
        vector<vector<int>> edges;
        vector<int> father(n + 1, 0);
        iota(father.begin(), father.end(), 0);

        int ans = 0;
        for(int i = 0; i < m; i++){
                int p, u, v, w;
                cin >> p >> u >> v >> w;
                if(p == 1){
                        merge(father, u, v);
                        ans += w;
                }else{
                        edges.push_back({u, v, w});
                }
        }

        sort(edges.begin(), edges.end(), [](auto &a, auto &b){ return a[2] < b[2]; });
        for(int i = 0; i < edges.size(); i++){
                if(merge(father, edges[i][0], edges[i][1])){
                        ans += edges[i][2];
                }
        }
        cout<<ans<<endl;
        return 0;
}